<?php

namespace app\portal\controller;

use app\admin\model\KnowledgeCate;
use app\common\controller\PortalBase;
use think\Request;
use think\Config;

class Knowledge extends PortalBase {
  protected $model,$modelCate;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Knowledge();
    $this->modelCate=new KnowledgeCate();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    if (!request()->isAjax()) {
      $cates = $this->modelCate->order('sort DESC,id DESC')->field('id,title,sort')->select();
      return view('',['cates'=>json_encode($cates)]);
    }
    $page = input('page/d', 0, 'abs');
    $cateId = input('cate/d', 0, 'abs');
    $search = input('search/s', '');
    $map = [];
    if ($search) {
      $map['title'] = ['like',
                       "%{$search}%"];
    }
    if($cateId>0){
      $map['cate_id']=$cateId;
    }


    $rows = $this->model->alias('k')
      ->join('__BASE_USER__ u', 'u.id=k.creator_uid', 'left')
      ->where($map)
      ->field('k.*,u.realname')
      ->order('k.sort DESC,k.id DESC')
      ->limit(10)->page($page)->select();
    $this->result($rows, 1);
  }


  public function view() {
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : NULL;
    if (!$row) $this->error(lang('data empty'));

    $row['realname'] = cmf_user_realname($row['creator_uid']);

    cmf_log('查看安全知识', $id, date('Y-m-d H:i'));

    if (request()->isAjax()) {
      $this->result($row, 1);
    }

    return view('', ['row' => $row]);
  }

}